package es.udc.emarketapp.emarket.model.usersFacade.actions;

import es.udc.emarketapp.emarket.model.client.dao.SQLClientDAO;
import es.udc.emarketapp.emarket.model.client.dao.SQLClientDAOFactory;
import es.udc.emarketapp.emarket.model.client.vo.ClientVO;
import es.udc.emarketapp.emarket.util.exceptions.model.NifCifAlreadyExistsException;
import es.udc.emarketapp.emarket.util.exceptions.model.UserNameAlreadyExistsException;
import java.sql.Connection;

import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.exceptions.ModelException;
import es.udc.fbellas.j2ee.util.sql.TransactionalPlainAction;

public class CreateClientAction implements TransactionalPlainAction {

    private ClientVO clientVO;

    public CreateClientAction(ClientVO clientVO) {
        this.clientVO = clientVO;
    }

    public Object execute(Connection connection)
            throws InternalErrorException, ModelException {
            //NifCifAlreadyExistsException,
            //UserNameAlreadyExistsException{

        SQLClientDAO clientDAO = SQLClientDAOFactory.getDAO();

        boolean existsClient = clientDAO.exists(connection, clientVO.getIdComprador());

        if (existsClient) {
            throw new UserNameAlreadyExistsException();
        } else {
            boolean existsNif = clientDAO.existsNifCif(connection, clientVO.getNifCif());
            if (existsNif) {

                throw new NifCifAlreadyExistsException();
            } else {
                return clientDAO.create(connection, clientVO);
            }
        }

    }
}
